package com.example.springboot.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelWriter;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletOutputStream;
import java.net.URLEncoder;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot.entity.HomestayImages;
import com.example.springboot.service.IBookingsService;
import com.example.springboot.service.IHomestayImagesService;
import com.example.springboot.service.IHomestayNewsService;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.springboot.common.Result;
import org.springframework.web.multipart.MultipartFile;
import com.example.springboot.entity.User;
import com.example.springboot.utils.TokenUtils;

import com.example.springboot.service.IHomestaysService;
import com.example.springboot.entity.Homestays;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 民宿表 前端控制器
 * </p>
 *
 * @author
 *
 */
@RestController
@RequestMapping("/homestays")
public class HomestaysController {
    @Resource
    private IHomestaysService homestaysService;
    @Resource
    private IHomestayImagesService iHomestayImagesService;
    @Resource
    private IHomestayNewsService iHomestayNewsService;
    @Resource
    private IBookingsService iBookingsService;
    @PostMapping
    public Result save(@RequestBody Homestays homestays) {

        // 保存主表信息
        homestaysService.saveOrUpdate(homestays);
        // 处理图片数组
        if (homestays.getImage() != null && !homestays.getImage().isEmpty()) {
//            // 删除原有的图片记录
            iHomestayImagesService.remove(new QueryWrapper<HomestayImages>()
                    .eq("homestay_id", homestays.getId()));
            // 保存新的图片记录
            List<HomestayImages> imagesList = new ArrayList<>();
            for (int i = 0; i < homestays.getImage().size(); i++) {
                HomestayImages image = new HomestayImages();
                image.setHomestayId(homestays.getId());
                image.setImg(homestays.getImage().get(i));
                image.setIsCover(0);
                image.setSortOrder(i + 1);  // 设置排序顺序
                imagesList.add(image);
            }
            iHomestayImagesService.saveBatch(imagesList);
        }
        return Result.success();
    }
    // 新增或者更新
    @PostMapping("status")
    public Result status(@RequestBody Homestays homestays) {
        QueryWrapper<Homestays> homestaysQueryWrapper = new QueryWrapper<>();
        homestaysQueryWrapper.eq("id",homestays.getId());
        homestaysService.update(homestays,homestaysQueryWrapper);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        homestaysService.removeById(id);
        return Result.success();
    }

    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        homestaysService.removeByIds(ids);
        return Result.success();
    }

    @GetMapping("/list")
    public Result findAll() {
        return Result.success(homestaysService.list());
    }

    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(homestaysService.getById(id));
    }

    @GetMapping("/page")
    public Result findPage(@RequestParam(defaultValue = "") String name,
                           @RequestParam Integer pageNum,
                           @RequestParam Integer pageSize) {
        QueryWrapper<Homestays> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        if (!"".equals(name)) {
            queryWrapper.like("name", name);
        }
        return Result.success(homestaysService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }

    /**
    * 导出接口
    */
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        // 从数据库查询出所有的数据
        List<Homestays> list = homestaysService.list();
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);

        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("Homestays信息表", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();

        }

    /**
     * excel 导入
     * @param file
     * @throws Exception
     */
    @PostMapping("/import")
    public Result imp(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        // 通过 javabean的方式读取Excel内的对象，但是要求表头必须是英文，跟javabean的属性要对应起来
        List<Homestays> list = reader.readAll(Homestays.class);

        homestaysService.saveBatch(list);
        return Result.success();
    }

    private User getUser() {
        return TokenUtils.getCurrentUser();
    }

    @GetMapping("/count")
    public Result count() {
        long count = homestaysService.count(); // 民宿数量
        long count1 = iHomestayNewsService.count(); // 民宿资讯数量
        long count2 = iBookingsService.count(); // 预订数量

        // 创建统计数据列表
        List<Map<String, Object>> statisticsData = new ArrayList<>();
        statisticsData.add(Map.of("title", "民宿数量", "value", count, "icon", "el-icon-s-home"));
        statisticsData.add(Map.of("title", "预订数量", "value", count2, "icon", "el-icon-s-order"));
        statisticsData.add(Map.of("title", "民宿资讯", "value", count1, "icon", "el-icon-s-marketing"));

        // 返回包含统计数据的 Result 对象
        return Result.success(statisticsData);
    }


}

